# Bar System 服务启动脚本
# 使用PowerShell后台运行服务

$ErrorActionPreference = "Continue"
$BaseDir = "D:\test\bar"

# 检查并创建日志目录
$LogDirs = @("$BaseDir\backend\logs", "$BaseDir\web\logs")
foreach ($dir in $LogDirs) {
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
    }
}

# 检查服务是否已运行
function Check-ServiceRunning {
    param([int]$Port)
    $connection = Test-NetConnection -ComputerName localhost -Port $Port -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
    return $connection.TcpTestSucceeded
}

# 启动后端服务
Write-Host "检查后端服务状态..." -ForegroundColor Cyan
if (Check-ServiceRunning -Port 38521) {
    Write-Host "后端服务已在运行 (端口 38521)" -ForegroundColor Yellow
} else {
    Write-Host "启动后端服务..." -ForegroundColor Green
    Start-Process powershell -ArgumentList "-NoProfile", "-WindowStyle Hidden", "-Command `"cd '$BaseDir\backend'; node server.js | Out-File -Append logs\service.log`"" -PassThru | Out-Null
    Start-Sleep -Seconds 3
    if (Check-ServiceRunning -Port 38521) {
        Write-Host "后端服务启动成功! (端口 38521)" -ForegroundColor Green
    } else {
        Write-Host "后端服务启动失败，请检查日志: $BaseDir\backend\logs\service.log" -ForegroundColor Red
    }
}

# 启动Web前端服务
Write-Host "`n检查Web前端服务状态..." -ForegroundColor Cyan
if (Check-ServiceRunning -Port 35280) {
    Write-Host "Web前端服务已在运行 (端口 35280)" -ForegroundColor Yellow
} else {
    Write-Host "启动Web前端服务..." -ForegroundColor Green
    Start-Process powershell -ArgumentList "-NoProfile", "-WindowStyle Hidden", "-Command `"cd '$BaseDir\web'; npm run dev -- --host | Out-File -Append logs\service.log`"" -PassThru | Out-Null
    Start-Sleep -Seconds 5
    if (Check-ServiceRunning -Port 35280) {
        Write-Host "Web前端服务启动成功! (端口 35280)" -ForegroundColor Green
    } else {
        Write-Host "Web前端服务启动失败，请检查日志: $BaseDir\web\logs\service.log" -ForegroundColor Red
    }
}

Write-Host "`n服务启动完成!" -ForegroundColor Cyan
Write-Host "后端API: http://localhost:38521" -ForegroundColor White
Write-Host "Web管理: http://localhost:35280" -ForegroundColor White
Write-Host "`n查看日志:" -ForegroundColor Cyan
Write-Host "  后端: $BaseDir\backend\logs\service.log" -ForegroundColor Gray
Write-Host "  Web: $BaseDir\web\logs\service.log" -ForegroundColor Gray
